import os.path

from DrissionPage import Chromium
from loguru import logger

import config
from lib.util import io_utils
from lib.util.http_utils import get_redirect_url_urllib


def fetch_pgsql_versions(browser: Chromium):
    try:
        tab = browser.new_tab()
        tab.get("https://www.enterprisedb.com/download-postgresql-binaries")

        container = tab.ele(".:container")
        version_blocks = container.children("tag:div")
        block_count = len(version_blocks)

        win_versions = list()
        mac_versions = list()
        for i in range(block_count):
            if i == block_count - 1:
                # 最后一个div快不是版本数据
                break
            version_block = version_blocks[i]
            version_text = version_block.ele("x://div/span").text.strip()
            if "not supported" in version_text.lower():
                # 跳过已经不支持的版本
                continue

            version_name = version_text[7:]
            logger.debug(f'{version_name}')

            download_items = version_block.eles("x://div/div/div")
            for item in download_items:
                tag_a = item.ele("x://a")
                download_url = tag_a.attr("href")
                download_url = get_redirect_url_urllib(download_url)
                filename = os.path.basename(download_url)
                platform = tag_a.ele("tag:img").attr("alt")
                if "Windows" in platform:
                    win_versions.append({"version": version_name, "name": filename, "url": download_url})
                elif "Mac" in platform:
                    mac_versions.append({"version": version_name, "name": filename, "url": download_url})

        win_data_file_path = os.path.join(config.base_dir, "data/pgsql-windows.json")
        io_utils.write_json(win_data_file_path, {'versions': win_versions})
        logger.debug(f"保存到版本数据到: {win_data_file_path}")

        mac_data_file_path = os.path.join(config.base_dir, "data/pgsql-mac.json")
        io_utils.write_json(mac_data_file_path, {'versions': mac_versions})
        logger.debug(f"保存到版本数据到: {mac_data_file_path}")
    except Exception:
        logger.exception("获取MySQL版本列表失败")
    finally:
        tab and tab.close()
